package com.bykj.property.sys.controller;

import com.bykj.property.controller.vo.response.ErrorCode;
import com.bykj.property.controller.vo.response.RespResult;
import com.bykj.property.sys.controller.vo.FileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author yiming
 * @title: FileController
 * @projectName property
 * @description: TODO
 * @date 2019/6/1823:11
 */
@Slf4j
@Api(tags = {"文件"})
@RestController
@RequestMapping("/admin")
public class FileController {
    @Value("${imagesPath}")
    private String filePath;
    @Value("${imagesMap}")
    private String fileMap;
    @Value("${imagehttp}")
    private String htp;
    @Value("${realm}")
    private String realm;
    @Value("${server.port}")
    private String port;
    @ApiOperation(value="文件上传")
    @RequestMapping(value = "/fileUpload",method = {RequestMethod.POST,RequestMethod.GET})
    public RespResult fileUpload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            RespResult.error(ErrorCode.FILE_UP_FAILE);
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
       // String filePath = "D://temp-rainy//"; // 上传后的路径
        String filename = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + filename);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInfo fileInfo=new FileInfo();
        fileInfo.setName(fileName);
        fileInfo.setUrl(htp+"://"+realm+":"+port+fileMap+"/"+ filename);
        return RespResult.ok(fileInfo);
    }


}
